package main

import (
	"fmt"
	"image-pull/router"
	"image-pull/tcpServer"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/gin-gonic/gin"
)

func startGinHTTP(httpAddr string) error {
	// 设置模式
	mode := gin.DebugMode
	if os.Getenv("GIN_MODE") == "release" {
		mode = gin.ReleaseMode
	}
	gin.SetMode(mode)
	// 创建gin路由
	server := gin.Default()
	server.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong")
	})
	server.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "欢迎使用image-pull服务")
	})
	// 配置路由组
	router.ConfigRouter(&server.RouterGroup)

	fmt.Printf("查看server运行状态： http://%s/debug/pprof\n", httpAddr)

	done := make(chan os.Signal, 1)
	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
	//启动服务器
	go func() {
		if err := server.Run(httpAddr); err != nil {
			log.Fatalf("HTTP Server error: %v\n", err)
		}
	}()
	//等待中断信号
	<-done
	return nil
}

func main() {
	serverAddr := os.Getenv("serverAddr")
	defaultServerPort := "30000"
	if serverAddr == "" {
		serverAddr = "0.0.0.0" + ":" + defaultServerPort
	} else {
		serverAddr = net.JoinHostPort(serverAddr, defaultServerPort)
	}

	httpAddr := os.Getenv("httpAddr")
	defaultHTTPPort := "8080"
	if httpAddr == "" {
		httpAddr = "0.0.0.0" + ":" + defaultHTTPPort
	} else {
		httpAddr = net.JoinHostPort(httpAddr, defaultHTTPPort)
	}
	// 启动tcp服务器
	listen, err := tcpServer.SerInit(serverAddr)
	if err != nil {
		fmt.Println("Failed to start tcp server:", err)
		os.Exit(1)
	}
	fmt.Printf(" Listening and serving tcp on %s\n", serverAddr)
	defer listen.Close()
	// 启动http服务器
	if err := startGinHTTP(httpAddr); err != nil {
		fmt.Println("Failed to start http server:", err)
		os.Exit(1)
	}
}
